package com.gmss.crawler.task;


import com.gmss.crawler.module.retraction.paper.domain.RPaper;
import com.gmss.crawler.module.retraction.paper.service.IRPaperService;
import com.gmss.crawler.service.AutoRetractionCrawlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 撤稿论文-异步
 */
@Slf4j
@Service
public class RetractionPaperTask {

    @Resource
    private AutoRetractionCrawlerService autoRetractionCrawlerService;

    @Resource
    private IRPaperService iRPaperService;

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1024,
            1024, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<>(4096), new ThreadPoolFactory("RetractionPaperTask-data-task"));


    public void submit(RPaper rPaper) {
        threadPoolExecutor.submit(new SyncDataThread(rPaper));
    }

    private class SyncDataThread implements Runnable {

        // 入参
        private RPaper rPaper;

        public SyncDataThread(RPaper rPaper) {
            this.rPaper = rPaper;
        }

        @Override
        public void run() {
            //撤稿论文
            try {
                Map<String, Object> map = autoRetractionCrawlerService.webOfScienceSearch(rPaper);
                if (MapUtils.isNotEmpty(map)) {
                    rPaper.setDescribeData(map.containsKey("abstractData") ? map.get("abstractData").toString() : null);
                    rPaper.setKeywords(map.containsKey("authorKeywrods") ? map.get("authorKeywrods").toString() : null);
                    if (StringUtils.isNotBlank(rPaper.getRelatedLinks())) {
                        if (map.containsKey("relatedLinks")) {
                            String links = rPaper.getRelatedLinks();
                            links = links + "," + map.get("relatedLinks").toString();
                            rPaper.setRelatedLinks(links);
                        }
                    } else {
                        if (map.containsKey("relatedLinks")) {
                            String links = map.get("relatedLinks").toString();
                            rPaper.setRelatedLinks(links);
                        }
                    }
                    iRPaperService.saveOrUpdate(rPaper);
                }
            } catch (Exception e) {
                log.info("RetractionPaperTask 异常：request:{}, Exception:{}", rPaper.getId(), e);

            }
        }
    }

    @PreDestroy
    public void destroy() {
        if (null != this.threadPoolExecutor) {
            this.threadPoolExecutor.shutdown();
        }
    }
}
